<template>
  <div class="parking-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6">
        <el-card shadow="hover" class="query-panel">
          <template #header>
            <div class="card-header">
              <span>停机能力分析</span>
            </div>
          </template>
          <el-form :model="queryForm" label-position="top">
            <el-form-item label="停机方式">
              <el-select v-model="queryForm.parkingMethod" placeholder="请选择停机方式" class="w-100">
                <el-option 
                  v-for="option in parkingMethodOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="飞机型号">
              <el-select v-model="queryForm.aircraftId" placeholder="请选择飞机型号" class="w-100">
                <el-option 
                  v-for="option in aircraftOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleQuery" class="w-100" :loading="loading">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="18">
        <el-card shadow="hover" class="chart-container">
          <template #header>
            <div class="card-header">
              <span>停机容量分析</span>
              <div class="legend">
                <div class="legend-item">
                  <div class="color-box current-capacity"></div>
                  <span>本场停机容量</span>
                </div>
                <div class="legend-item">
                  <div class="color-box historical-capacity"></div>
                  <span>过往停机容量</span>
                </div>
                <div class="legend-item">
                  <div class="color-box aircraft-count"></div>
                  <span>部署飞机数量</span>
                </div>
              </div>
            </div>
          </template>
          
          <div class="loading-container" v-if="loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>加载中...</p>
          </div>
          
          <div class="error-container" v-else-if="error">
            <el-icon><CircleClose /></el-icon>
            <p>{{ errorMessage }}</p>
            <el-button type="primary" size="small" @click="loadData">重试</el-button>
          </div>
          
          <div class="empty-container" v-else-if="!parkingData.length">
            <el-empty description="暂无数据" />
          </div>
          
          <div id="parking-chart" class="chart" v-else ref="chartContainer"></div>
          
          <div class="capacity-details" v-if="!loading && !error && selectedAirport">
            <h3>{{ selectedAirport.name }} 详细数据</h3>
            <el-descriptions border>
              <el-descriptions-item label="本场停机量">{{ selectedAirport.current_capacity }}</el-descriptions-item>
              <el-descriptions-item label="过往停机量">{{ selectedAirport.historical_total }}</el-descriptions-item>
              <el-descriptions-item label="部署飞机数量">{{ selectedAirport.aircraft_count }}</el-descriptions-item>
              <el-descriptions-item label="垂直停机容量">{{ selectedAirport.historical_capacity.vertical }}</el-descriptions-item>
              <el-descriptions-item label="平行停机容量">{{ selectedAirport.historical_capacity.parallel }}</el-descriptions-item>
              <el-descriptions-item label="顶推停机容量">{{ selectedAirport.historical_capacity.pushback }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getParkingCapacity } from '@/api/analysis'
import { Loading, CircleClose } from '@element-plus/icons-vue'

export default {
  name: 'ParkingView',
  components: {
    Loading,
    CircleClose
  },
  setup() {
    const queryForm = ref({
      parkingMethod: '',
      aircraftId: null
    })
    
    const parkingMethodOptions = ref([])
    const aircraftOptions = ref([])
    const parkingData = ref([])
    const loading = ref(true)
    const selectedAirport = ref(null)
    const error = ref(false)
    const errorMessage = ref('加载数据失败，请稍后重试')
    const chartContainer = ref(null)
    
    let chart = null
    
    const initChart = () => {
      if (chart) {
        chart.dispose()
        chart = null
      }
      
      if (!chartContainer.value) {
        console.error('找不到图表容器元素引用')
        return false
      }
      
      try {
        chart = echarts.init(chartContainer.value)
        
        // 添加点击事件
        chart.on('click', (params) => {
          // 查找对应机场的详细数据
          const airport = parkingData.value.find(item => item.name === params.name)
          if (airport) {
            selectedAirport.value = airport
          }
        })
        
        return true
      } catch (error) {
        console.error('初始化图表失败:', error)
        return false
      }
    }
    
    const updateChart = async (data) => {
      // 确保有数据可供展示
      if (!data || data.length === 0) {
        console.warn('没有数据可供展示')
        return
      }
      
      // 等待DOM更新完成
      await nextTick()
      
      // 初始化图表，如果失败则直接返回
      if (!initChart()) {
        return
      }
      
      // 准备数据
      const names = data.map(item => item.name)
      const currentCapacity = data.map(item => item.current_capacity || 0)
      const historicalCapacity = data.map(item => item.historical_total || 0)
      const aircraftCount = data.map(item => item.aircraft_count || 0)
      
      // 计算最大值，用于设置Y轴范围
      const maxValue = Math.max(
        ...currentCapacity, 
        ...data.map(item => (item.current_capacity || 0) + (item.historical_total || 0)),
        ...aircraftCount,
        1 // 确保至少为1，避免都是0的情况
      )
      
      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const airport = data.find(item => item.name === params[0].name)
            let html = `<div style="font-weight:bold;margin-bottom:8px">${params[0].name}</div>`
            
            html += `<div style="margin-bottom:3px">
                      <span style="display:inline-block;width:10px;height:10px;background-color:#5470c6;margin-right:5px;"></span>
                      本场停机容量: ${airport.current_capacity || 0}
                     </div>`
            
            html += `<div style="margin-bottom:3px">
                      <span style="display:inline-block;width:10px;height:10px;background-color:#91cc75;margin-right:5px;"></span>
                      过往停机容量: ${airport.historical_total || 0}
                     </div>`
                     
            html += `<div style="margin-bottom:3px">
                      <span style="display:inline-block;width:10px;height:10px;background-color:#ee6666;margin-right:5px;"></span>
                      部署飞机数量: ${airport.aircraft_count || 0}
                     </div>`
            
            html += `<div style="margin-top:8px">
                      <span style="font-size:12px;color:#999">点击柱状图查看详情</span>
                     </div>`
                     
            return html
          }
        },
        legend: {
          show: false // 使用自定义图例
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: names,
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '飞机数量',
          max: maxValue * 1.1 // 留出10%的空间
        },
        series: [
          {
            name: '本场停机容量',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: '#5470c6'
            },
            data: currentCapacity
          },
          {
            name: '过往停机容量',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: '#91cc75'
            },
            data: historicalCapacity
          },
          {
            name: '部署飞机数量',
            type: 'bar',
            itemStyle: {
              color: '#ee6666'
            },
            data: aircraftCount
          }
        ]
      }
      
      try {
        // 应用配置
        chart.setOption(option)
      } catch (error) {
        console.error('设置图表选项时出错:', error)
      }
      
      // 默认选中第一个机场
      if (data.length > 0) {
        selectedAirport.value = data[0]
      }
    }
    
    const loadData = async (params = {}) => {
      try {
        loading.value = true
        error.value = false
        
        const response = await getParkingCapacity(params)
        
        // 更新数据
        parkingData.value = response.data
        parkingMethodOptions.value = response.parkingMethod.options
        aircraftOptions.value = response.aircraft.options
        
        // 如果未选择飞机型号，使用接口返回的默认值
        if (!queryForm.value.aircraftId) {
          queryForm.value.aircraftId = response.aircraft.selected.id
        }
        
        // 使用nextTick确保DOM已更新
        loading.value = false
        await nextTick()
        updateChart(response.data)
      } catch (error) {
        console.error('加载停机数据失败:', error)
        loading.value = false
        error.value = true
        errorMessage.value = error.message || '加载数据失败，请稍后重试'
      }
    }
    
    const handleQuery = () => {
      const params = {
        aircraft_id: queryForm.value.aircraftId,
        parking_method: queryForm.value.parkingMethod
      }
      loadData(params)
    }
    
    onMounted(() => {
      // 加载初始数据
      loadData()
      
      // 添加窗口大小变化的监听器
      const handleResize = () => {
        if (chart) {
          try {
            chart.resize()
          } catch (error) {
            console.error('调整图表大小时出错:', error)
          }
        }
      }
      
      window.addEventListener('resize', handleResize)
      
      // 在组件卸载时删除事件监听器
      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize)
        
        if (chart) {
          try {
            chart.dispose()
          } catch (error) {
            console.error('销毁图表时出错:', error)
          } finally {
            chart = null
          }
        }
      })
    })
    
    return {
      queryForm,
      handleQuery,
      parkingMethodOptions,
      aircraftOptions,
      loading,
      selectedAirport,
      parkingData,
      error,
      errorMessage,
      loadData,
      chartContainer
    }
  }
}
</script>

<style scoped>
.parking-container {
  padding: 20px;
}

.query-panel, .chart-container {
  height: 100%;
  min-height: 600px;
}

.chart {
  height: 500px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.w-100 {
  width: 100%;
}

.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 500px;
}

.loading-container .el-icon,
.error-container .el-icon {
  font-size: 32px;
  margin-bottom: 16px;
  color: var(--el-color-primary);
}

.error-container .el-icon {
  color: var(--el-color-danger);
}

.error-container p {
  margin-bottom: 16px;
  color: var(--el-color-danger);
}

.legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.color-box {
  width: 12px;
  height: 12px;
  margin-right: 4px;
  border-radius: 2px;
}

.current-capacity {
  background-color: #5470c6;
}

.historical-capacity {
  background-color: #91cc75;
}

.aircraft-count {
  background-color: #ee6666;
}

.capacity-details {
  margin-top: 20px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .query-panel {
    margin-bottom: 20px;
  }
}
</style> 